import Ember from 'ember';
import FormState from 'emberworkspace/utils/form-state';
import tuaUtil from 'emberworkspace/utils/tua-util';
import ItemViewMinxin from 'emberworkspace/mixins/item-view-mixin';

export default Ember.Controller.extend(ItemViewMinxin, {
  indexController: Ember.inject.controller('treenodes.index'),
  treeModel: Ember.computed.reads('indexController.model'),
  formState: FormState.create({
    btnName: "保存",
    successMsg: "成功",
    failMsg: "失败"
  }),
  menus: Ember.computed(function() {
    return [this.get('commonMenus')[0]];
  }),
  gotoList() {
    var isNewRecord = this.get('isNewRecord'),
      model = this.get('model'),
      editingModel = this.get('editingModel'),
      treeModel = this.get('treeModel'),
      indexer = treeModel.get('__indexer');

    // Object.keys(indexer).forEach((k) => {
    //   if (indexer[k].get('isSelected')) {
    //     indexer[k].set('isSelected', false);
    //   }
    // });

    if (isNewRecord) {
      this.transitionToRoute("treenodes.index.children", treeModel, model);
    } else {
      if (model.get('p')) {
        this.transitionToRoute("treenodes.index.children", treeModel, model.get('p'));
      } else {
        this.transitionToRoute("treenodes.index.children", treeModel, model);
      }
    }
  },
  actions: {
    menuClicked: function(mname) {
      var model = this.get('model'),
        treeModel = this.get('treeModel');

      if (mname === 'gotolist') {
        this.gotoList();
      }
    },
    submitForm() {
      var self = this,
        model = this.get('model'), // this is parent node.
        editingModel = this.get('editingModel'),
        treeModel = this.get('treeModel'),
        formState = this.get('formState'),
        isNewRecord = this.get('isNewRecord'),
        data,
        err;

      if (isNewRecord) {
        data = tuaUtil.createAction(treeModel.get('id'), model.get('id'), editingModel.get('n'), editingModel.get('v'));
      } else {
        data = tuaUtil.editAction(treeModel.get('id'), model.get('id'), editingModel.get('n'), editingModel.get('v'));
      }

      if (!editingModel.get('n')) {
        err = {
          fn: "节点名称",
          msg: "不能空"
        };
        formState.setError(err);
      }

      tuaUtil.ajax(treeModel, data)
        .done(function(data, textStatus, jqXHR) {
          treeModel.alterNode(data);
          formState.success();
          self.gotoList();
        })
        .fail(function(qXHR, textStatus, errorThrown) {
          formState.failure();
        });
    }
  }
});
